<?php

namespace App\Http\Controllers\API\UI;

use App\Http\Controllers\Controller;
use App\Miya\Models\ChatRecord;
use App\Miya\Tools\NoteTool;
use GuzzleHttp\Client;
use Ichynul\Configx\ConfigxModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class ChatController extends Controller
{
    public function takeMsg()
    {
        if (request()->input('token') != md5(now()->format('YmdH'))) {
            return ['status' => false, 'msg' => '信息提交失败,Token过期,请刷新页面再次尝试!'];
        }

        $data = request()->only(['phone', 'content']);
        $data['ip'] = request()->getClientIp();
        $result = ChatRecord::create($data);

        $key = 'note.balance';
        if ($result) {
            //短信通知网站管理员
            if (config('setting.phone_hint') && config('setting.phone') && config($key) > 0) {
                if (config($key) != cache()->get($key)) return;
                NoteTool::sendMsg('216522', config('setting.phone'), '#web#=' . config('web.name'));

                $config = ConfigxModel::whereName($key)->first();
                $config->value--;
                $config->save();

                $num = Cache::get($key);
                cache()->set($key, $num - 1);
            }

            //同步到oms
            try {
                // 同步信息到oms
                $this->syncOms($data);
            } catch (\Exception $exception) {
                //啥也不做
            }
        }
        return [
            'status' => true,
            'msg' => '您好,咨询人员较多,为了不耽误您的咨询效果,您可以留下您的联系方式(电话或者微信)稍后我们这边专业同事直接对接您!'
        ];
    }

    protected function syncOms($data)
    {
        if (!$data['phone']) return;

        if (config('setting.phone_hint')) {
            if (config('setting.phone') && config('note.balance') > 0) {
                $data['is_remind'] = 3;
            } else {
                $data['is_remind'] = 2;
            }
        } else {
            $data['is_remind'] = 1;
        }
        $data['order_id'] = json_decode(cache()->get('oms_order'), true)['id'];

        $client = new Client();
        $client->request('POST', config('miya.chat_record_url'), ['form_params' => $data]);
    }
}
